<template>
  <div class="control">
    <van-nav-bar title="继电器控制" left-arrow @click-left="onClickLeft" />

    <van-tabs type="line" animated swipeable>
      <van-tab title="施肥继电器">
        <div class="empty" v-if="shifeiList.length === 0">
          <van-empty description="暂无内容" />
        </div>
        <div v-else class="control-content">
          <van-cell-group inset>
            <van-cell
              center
              v-for="item in shifeiList"
              :key="item"
              class="control-content-cell"
              :title="item.deviceName"
              :label="item.label"
            >
              <template #right-icon>
                <van-switch
                  @click="handleOnSwitch(1, item)"
                  :disabled="item.now"
                  :loading="item.loading"
                  v-model="item.state"
                  size="24"
                />
              </template>
            </van-cell>
          </van-cell-group>
        </div>
      </van-tab>
      <van-tab title="打药继电器">
        <div class="empty" v-if="dayaoList.length === 0">
          <van-empty description="暂无内容" />
        </div>
        <div v-else class="control-content">
          <van-cell-group inset>
            <van-cell
              center
              v-for="item in dayaoList"
              :key="item"
              class="control-content-cell"
              :title="item.deviceName"
              :label="item.label"
            >
              <template #right-icon>
                <van-switch
                  @click="handleOnSwitch(2, item)"
                  :disabled="!item.now"
                  :loading="item.loading"
                  v-model="item.state"
                  size="24"
                />
              </template>
            </van-cell>
          </van-cell-group>
        </div>
      </van-tab>
      <van-tab title="水泵继电器">
        <div class="empty" v-if="shuibengList.length === 0">
          <van-empty description="暂无内容" />
        </div>
        <div v-else class="control-content">
          <van-cell-group inset>
            <van-cell
              center
              v-for="item in shuibengList"
              :key="item"
              class="control-content-cell"
              :title="KeyName(item.deviceName)"
              :label="item.label"
            >
              <template #right-icon>
                <van-switch
                  @click="handleOnSwitch(3, item)"
                  :disabled="!item.now"
                  :loading="item.loading"
                  v-model="item.state"
                  size="24"
                />
              </template>
            </van-cell>
          </van-cell-group>
        </div>
      </van-tab>
    </van-tabs>
    <div class="control-content-tip">数据更新时间：{{ lastTime }}</div>
  </div>
</template>

<script>
import { stringToByte } from "@/utils/dateCon";
import { Dialog } from "vant";
import { Toast } from "vant";
export default {
  data() {
    return {
      lastTime: "",
      shifeiList: [],
      dayaoList: [],
      shuibengList: [],
      paramsRes: "",
      keyName: {
        水泵施肥1: "增压水泵",
        水泵施肥2: "搅拌电机",
        水泵施肥3: "主水阀门",
        水泵施肥4: "肥料阀门",
        水泵打药1: "增压水泵",
        水泵打药2: "搅拌电机",
        水泵打药3: "主水阀1",
        水泵打药4: "主水阀2",
      },
    };
  },
  watch: {
    paramsRes: {
      handler(newVal, oldVal) {
        this.dataConver(newVal);
      },
      deep: true,
    },
  },
  created() {
    this.paramsRes = this.$route.params;
    this.dataConver(this.paramsRes);
  },
  methods: {
    KeyName(key) {
      return this.keyName[key];
    },
    onClickLeft() {
      this.$router.back();
    },
    handleOnSwitch(key, item) {
      console.log(item.state);
      // if (!this.paramsRes.mqttMsg.now || item.loading) {
      //   console.log("return");
      //   return;
      // }
      var hex;
      var name = item.deviceName;
      item.loading = true;

      switch (key) {
        case 1:
          var index = Number(
            name.substring(name.indexOf("肥") + 1, name.length)
          )
            .toString(16)
            .padStart(2, "0")
            .toUpperCase();
          //开关关闭
          if (item.state === true) {
            hex = "A1 02 00 01 00 " + index + " 1A";
          } else if (item.state === false) {
            hex = "A1 02 01 01 00 " + index + " 1A";
          }
          break;
        case 2:
          var index = Number(
            name.substring(name.indexOf("药") + 1, name.length)
          )
            .toString(16)
            .padStart(2, "0")
            .toUpperCase();
          //开关关闭
          if (item.state === true) {
            hex = "A1 02 00 02 00 " + index + " 1A";
          } else if (item.state === false) {
            hex = "A1 02 01 02 00 " + index + " 1A";
          }
          break;
        case 3:
          if (name[2] === "施") {
            var index = Number(
              name.substring(name.indexOf("肥") + 1, name.length)
            )
              .toString(16)
              .padStart(2, "0")
              .toUpperCase();
            //开关关闭
            if (item.state === true) {
              hex = "A1 02 00 03 00 " + index + " 1A";
            } else if (item.state === false) {
              hex = "A1 02 01 03 00 " + index + " 1A";
            }
          } else {
            var index = Number(
              name.substring(name.indexOf("药") + 1, name.length)
            )
              .toString(16)
              .padStart(2, "0")
              .toUpperCase();
            //开关关闭
            if (item.state === true) {
              hex = "A1 02 00 03 01 " + index + " 1A";
            } else if (item.state === false) {
              hex = "A1 02 01 03 01 " + index + " 1A";
            }
          }

          break;
        default:
          break;
      }
      console.log(hex);
      var send = stringToByte(hex);
      this.$mqtt.publishHex(this.paramsRes.deviceInfo.mqttSub, send);
    },
    dataConver(newVal) {
      console.log(newVal);
      this.lastTime = newVal.mqttMsg.time;
      // 首先判断开关与现有的个数是否一致，若不一致则清空现有数据重新添加。
      if (this.shifeiList.length === newVal.mqttMsg.shifeiState.length) {
        // 一致的情况下，进行for循环遍历
        for (
          let index = 0;
          index < newVal.mqttMsg.shifeiState.length;
          index++
        ) {
          const element = newVal.mqttMsg.shifeiState[index];
          var sItem = element.split(";");
          // 在这里判断情况 如果该按钮处于正在加载的状态则
          if (this.shifeiList[index].loading) {
            var state = sItem[4] === "关" ? false : true;
            if (this.shifeiList[index].overtime > 5) {
              // 判断是否超时，如果超时了则根据目前最新的来
              this.shifeiList[index].state = sItem[4] === "关" ? false : true;
              Toast.fail("超时，操作失败");
              // 此处给个提示
            } else if (state == this.shifeiList[index].state) {
              //  判断是否修改成功。这里需要实验一下 修改成功的情况
              this.shifeiList[index].loading = false;
              this.shifeiList[index].overtime = 0;
            } else {
              // 修改不成功的情况
              this.shifeiList[index].overtime++;
            }
          }
        }
      } else {
        // 此部分无改动
        this.shifeiList = [];
        try {
          newVal.mqttMsg.shifeiState.forEach((element) => {
            var sItem = element.split(";");
            const item = {
              label: sItem[0] + " | " + sItem[3] + "线",
              deviceName: sItem[1],
              state: sItem[4] === "关" ? false : true,
              loading: false,
              overtime: 0,
              now: newVal.mqttMsg.now,
            };
            this.shifeiList.push(item);
          });
        } catch (error) {}
      }

      // 首先判断开关与现有的个数是否一致，若不一致则清空现有数据重新添加。
      if (this.dayaoList.length === newVal.mqttMsg.dayaoState.length) {
        // 一致的情况下，进行for循环遍历
        for (
          let index = 0;
          index < newVal.mqttMsg.dayaoState.length;
          index++
        ) {
          const element = newVal.mqttMsg.dayaoState[index];
          var sItem = element.split(";");
          // 在这里判断情况 如果该按钮处于正在加载的状态则
          if (this.dayaoList[index].loading) {
            var state = sItem[4] === "关" ? false : true;
            if (this.dayaoList[index].overtime > 5) {
              // 判断是否超时，如果超时了则根据目前最新的来
              this.dayaoList[index].state = sItem[4] === "关" ? false : true;
              Toast.fail("超时，操作失败");
              // 此处给个提示
            } else if (state == this.dayaoList[index].state) {
              //  判断是否修改成功。这里需要实验一下 修改成功的情况
              this.dayaoList[index].loading = false;
              this.dayaoList[index].overtime = 0;
            } else {
              // 修改不成功的情况
              this.dayaoList[index].overtime++;
            }
          }
        }
      } else {
        // 此部分无改动
        this.dayaoList = [];
        try {
          newVal.mqttMsg.dayaoState.forEach((element) => {
            var sItem = element.split(";");
            const item = {
              label: sItem[0] + " | " + sItem[3] + "线",
              deviceName: sItem[1],
              state: sItem[4] === "关" ? false : true,
              loading: false,
              overtime: 0,
              now: newVal.mqttMsg.now,
            };
            this.dayaoList.push(item);
          });
        } catch (error) {}
      }

      // 首先判断开关与现有的个数是否一致，若不一致则清空现有数据重新添加。
      if (this.shuibengList.length === newVal.mqttMsg.shuibengState.length) {
        // 一致的情况下，进行for循环遍历
        for (
          let index = 0;
          index < newVal.mqttMsg.shuibengState.length;
          index++
        ) {
          const element = newVal.mqttMsg.shuibengState[index];
          var sItem = element.split(";");
          // 在这里判断情况 如果该按钮处于正在加载的状态则
          if (this.shuibengList[index].loading) {
            var state = sItem[4] === "关" ? false : true;
            if (this.shuibengList[index].overtime > 5) {
              // 判断是否超时，如果超时了则根据目前最新的来
              this.shuibengList[index].state = sItem[4] === "关" ? false : true;
              Toast.fail("超时，操作失败");
              // 此处给个提示
            } else if (state == this.shuibengList[index].state) {
              //  判断是否修改成功。这里需要实验一下 修改成功的情况
              this.shuibengList[index].loading = false;
              this.shuibengList[index].overtime = 0;
            } else {
              // 修改不成功的情况
              this.shuibengList[index].overtime++;
            }
          }
        }
      } else {
        // 此部分无改动
        this.shuibengList = [];
        try {
          newVal.mqttMsg.shuibengState.forEach((element) => {
            var sItem = element.split(";");
            const item = {
              label: sItem[0] + " | " + sItem[3] + "线",
              deviceName: sItem[1],
              state: sItem[4] === "关" ? false : true,
              loading: false,
              overtime: 0,
              now: newVal.mqttMsg.now,
            };
            this.shuibengList.push(item);
          });
        } catch (error) {}
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.control {
  height: 100%;
  width: 100%;
  overflow-y: auto;
  position: absolute;
  &-content {
    // margin-top: 20px;
    // &-cell{
    padding-top: 20px;
    // }
    &-tip {
      text-align: center;
      margin: 20px 20px 6px 26px;
      color: #fff;
    }
  }
}
.empty {
  z-index: 1;
  height: auto;
  border-radius: 20px;
  margin: 20px 20px;
  box-shadow: 0px 0px 12px 0 rgb(0 0 0 / 8%);
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(20px) saturate(180%);
}
</style>
